--[[
    @Author       : baidwwy
    @Date         : 2020-09-24 04:00:35
    @LastEditTime : 2021-02-21 19:32:34
--]]
local gge = package.loadlib("ggelua", "luaopen_ggelua")()
local lfs = require("lfs")
local MD5 = require("md5").sumhexa
local outpath = gge.ansitoutf8(arg[1])

print("当前目录:"..outpath)
print("请输入打包的目录:")
local name = io.stdin:read()
print("请输入打包密码:")
local password = io.stdin:read()

function dir(path,...)
    if select("#", ...)>0 then
        path = path:format(...)
    end
    local lfs = require("lfs")
    path = gge.utf8toansi(path)
    local dir,u = lfs.dir(path)
    local pt = {}
    return function ()
        repeat
            local file = dir(u)
            if file then
                local f = path..'/'..file
                local attr = lfs.attributes (f)
                if attr and attr.mode == "directory" then
                    if file ~= "." and file ~= ".." then
                        table.insert(pt, f)
                    end
                    file = "."
                else
                    return gge.ansitoutf8(f)
                end
            elseif pt[1] then
                path = table.remove(pt, 1)
                dir,u = lfs.dir(path)
                file = "."
            end
        until file ~= "."
    end
end

function readfile(path)
    local file<close> = io.open(gge.utf8toansi(path), 'rb');
    if file then
        return file:read('a')
    end
end

os.remove(string.format("%s/%s.db",outpath,name))
local sqlite3 = require("lsqlite3")
local SQL = sqlite3.open(string.format("%s/%s.db",outpath,name))

if password~='' then
    SQL:exec(string.format("PRAGMA key = '%s';", password))
end

SQL:exec[[
    CREATE TABLE "main"."file" (
        "path"  TEXT,
        "md5"  TEXT,
        PRIMARY KEY ("path")
    );

    CREATE UNIQUE INDEX "main"."spath"
    ON "file" ("path" ASC);

    CREATE TABLE "main"."data" (
        "type"  INTEGER DEFAULT 0,
        "md5"  TEXT,
        "time"  INTEGER,
        "size"  INTEGER,
        "size2"  INTEGER,
        "data"  BLOB,
        PRIMARY KEY ("md5")
    );

    CREATE UNIQUE INDEX "main"."smd5"
    ON "data" ("md5" ASC);
]]
    
SQL:exec("BEGIN")
    for path in dir(name) do
        local time = lfs.attributes(gge.utf8toansi(path),'modification')
        local data = readfile(path)
        local md5 = MD5(data)
        
        path = path:gsub(name.."/","")
        
        SQL:exec(string.format("insert into file(path,md5) values('%s','%s')",
            path,
            md5
        ))
        
        SQL:exec(string.format("insert into data(md5,time,size) values('%s','%d','%d')",
            md5,
            time,
            #data
        ))

        local vm = SQL:prepare(string.format("update data set data=? where md5='%s'",md5))
        vm:bind_blob(1,data)
        vm:step()
        
        print(time,md5,path)
    end
SQL:exec("COMMIT")

print('打包完成')
os.exit()